package com.qiyu.tech.gateway.controller;

import com.qiyu.tech.gateway.auth.BlackListCheckDTO;
import com.qiyu.tech.gateway.auth.IBlackListCacheManager;
import com.qiyu.tech.gateway.dao.po.BlackListPO;
import com.qiyu.tech.gateway.service.IBlackListCheckService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author linhao
 * @Date created in 10:40 下午 2021/3/16
 */
@RestController
public class CommonController {

    @Resource
    private IBlackListCheckService iBlackListCheckService;

    @Resource
    private IBlackListCacheManager iBlackListCacheManager;

    @GetMapping(value = "/check")
    public boolean check(HttpServletRequest request, HttpServletResponse response){
        BlackListCheckDTO blackListCheckDTO = new BlackListCheckDTO();
        String token = request.getHeader("auth-token");
        if(token!=null){
            blackListCheckDTO.setType((short) 0);
            blackListCheckDTO.setIdentification(token);
            if(iBlackListCheckService.existInBlackList(blackListCheckDTO)){
                return true;
            }
        }

        String userAgent = request.getHeader("ua");
        if(userAgent!=null){
            blackListCheckDTO.setType((short) 2);
            blackListCheckDTO.setIdentification(userAgent);
            if(iBlackListCheckService.existInBlackList(blackListCheckDTO)){
                return true;
            }
        }
        return false;
    }

    @PostMapping(value = "/insert-node")
    public boolean insertNode(BlackListPO blackListPO){
        return iBlackListCacheManager.insertOne(blackListPO);
    }
}
